package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.DbdkExcelListener;
import cn.stylefeng.guns.sys.core.listener.JtgzExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Ksda;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Yfd;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDbdk;
import cn.stylefeng.guns.sys.modular.system.entity.BtyHp;
import cn.stylefeng.guns.sys.modular.system.entity.BtyJtgz;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyJtgzMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDbdkParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyJtgzParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDbdkResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyJtgzResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyJtgzService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 控制器
 * @author liuy
 * @Date 2022-02-17 14:40:37
 */
@Controller
@RequestMapping("/btyJtgz")
public class BtyJtgzController extends BaseController {

    private String PREFIX = "/modular/system/btyJtgz";

    @Autowired
    private BtyJtgzService btyJtgzService;
    @Resource
    private BtyJtgzMapper jtgzMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyJtgz.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyJtgz_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyJtgz_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyJtgzParam btyJtgzParam) {
        this.btyJtgzService.add(btyJtgzParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyJtgzParam btyJtgzParam) {
        this.btyJtgzService.update(btyJtgzParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyJtgzParam btyJtgzParam) {
        this.btyJtgzService.delete(btyJtgzParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyJtgzParam btyJtgzParam) {
        BtyJtgz detail = this.btyJtgzService.getById(btyJtgzParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-02-17
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyJtgzParam btyJtgzParam) {
        return this.btyJtgzService.findPageBySpec(btyJtgzParam);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file, BtyJtgzParam param) {
        JsonResult jsonResult = new JsonResult();
        if(ToolUtil.isEmpty(param.getZdrq())){
            jsonResult.setState(0);
            jsonResult.setErrmsg("请先选择制单日期！");
            return jsonResult;
        }
        //导入之前删掉之前的数据
        jtgzMapper.delete(new QueryWrapper<>());
        String zdrq=param.getZdrq();
        try {
            JtgzExcelListener jtgzExcelListener=new JtgzExcelListener(btyJtgzService);
            EasyExcel.read(file.getInputStream(), BtyJtgz.class, jtgzExcelListener).sheet(0).doRead();
            //导入成功之后生成计提工资凭证
            List<BtyJtgzResult>list=btyJtgzService.jtgzList();
            for (BtyJtgzResult jtgzResult : list) {
                BigDecimal amount=jtgzResult.getAmount();
                //用友大区编号
                String bh=jtgzResult.getCode();
                //妖码
                String yaoma=jtgzResult.getYaoma();
                //店名
                String dm=jtgzResult.getDm();
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("trantype", "code");
                // 系统编码
                headers.add("system", "001");
                // 用户
                headers.add("usercode", "15253172037");
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                StringBuilder sb=new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");
                //计提工资凭证
                sb.append("                {\n" +
                        "                    \"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+yaoma+"'\n" +//部门档案辅助核算编码
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\"\",\n" +
                        "                    \"debitamount\":\""+amount+"\",\n" +//借方金额
                        "                    \"explanation\":\"新店计提工资\",\n" +//借方摘要
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"660103\",\n" +//借方科目编码
                        "                    \"pk_currtype\":\"CNY\"\n" +
                        "                }," +
                        "{\n" +
                        "\t\t\t\t\"ass\":[\n" +
                        "                        {\n" +
                        "                            \"checktypecode\":\"2\",\n" +
                        "                            \"checkvaluecode\":'"+yaoma+"'\n" +//部门档案辅助核算编码
                        "                        }\n" +
                        "                    ],\n" +
                        "                    \"creditamount\":\""+amount+"\",\n" +//贷方金额
                        "                    \"creditquantity\":\"\",\n" +
                        "                    \"debitamount\":\"\",\n" +
                        "                    \"debitquantity\":\"\",\n" +
                        "                    \"detailindex\":\"\",\n" +
                        "                    \"excrate1\":\"\",\n" +
                        "                    \"explanation\":\"新店计提工资\",\n" +//贷方摘要
                        "                    \"localcreditamount\":\"\",\n" +
                        "                    \"localdebitamount\":\"\",\n" +
                        "                    \"pk_accsubj\":\"221101\",\n" +//贷方科目编码
                        "                    \"pk_currtype\":\"CNY\",\n" +
                        "                    \"price\":\"\"\n" +
                        "                },\n");
                sb.append("            ],\n" +
                        "            \"pk_corp\":"+bh+",\n" +//用友大区编号
                        "            \"pk_glorgbook\":\""+bh+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +//用友制单日期
                        "        }\n" +
                        "    ]\n" +
                        "}");
                //System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if(status.equals("falied")){
                    String errormsg = jo.get("errormsg").getAsString();
                    BtyJtgz jtgz=btyJtgzService.getOne(new QueryWrapper<BtyJtgz>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(jtgz)){
                        jtgz.setErrormsg(errormsg);
                        btyJtgzService.updateById(jtgz);
                    }
                }else{
                    BtyJtgz jtgz=btyJtgzService.getOne(new QueryWrapper<BtyJtgz>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(jtgz)){
                        jtgz.setFlag(1);
                        btyJtgzService.updateById(jtgz);
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

    @RequestMapping("/listSearchExport")
    @ResponseBody
    public List<BtyJtgzResult> listSearchExport (BtyJtgzParam param){
        List<BtyJtgzResult> list= btyJtgzService.customList(param);
        return list;
    }

}


